<template>
  <div class="register-container">
    <el-row class="register-wrapper" justify="center" align="middle">
      <el-col :xs="24" :sm="18" :md="12" :lg="10">
        <el-card class="register-card" shadow="hover">
          <!-- 页面标题 -->
          <div class="register-header">
            <h1 class="title">加入我们</h1>
            <p class="subtitle">选择您的注册身份</p>
          </div>

          <!-- 身份选择卡片 -->
          <div class="identity-cards">
            <!-- 普通用户卡片 -->
            <el-card class="identity-card user-card" shadow="hover" @click="selectIdentity('user')"
              :class="{ selected: selectedIdentity === 'user' }">
              <div class="card-content">
                <el-icon :size="60" class="card-icon">
                  <UserFilled />
                </el-icon>
                <h3 class="card-title">普通用户</h3>
                <p class="card-desc">购买商品、查看资讯、参与社区互动</p>
                <el-button plain @click="dialogFormVisibleUser = true" type="primary" size="large" round
                  v-show="selectedIdentity === 'user'">
                  立即注册
                </el-button>
              </div>
            </el-card>

            <!-- 商家卡片 -->
            <el-card class="identity-card merchant-card" shadow="hover" @click="selectIdentity('merchant')"
              :class="{ selected: selectedIdentity === 'merchant' }">
              <div class="card-content">
                <el-icon :size="60" class="card-icon">
                  <Shop />
                </el-icon>
                <h3 class="card-title">商家入驻</h3>
                <p class="card-desc">发布商品、管理订单、开展营销活动</p>
                <el-button plain @click="dialogFormVisibleSeller = true" type="success" size="large" round
                  v-show="selectedIdentity === 'merchant'">
                  商家认证
                </el-button>
              </div>
            </el-card>
          </div>

          <!-- 已有账号引导 -->
          <div class="login-guide">
            <span class="tip">已有账号？</span>
            <el-link type="primary" :underline="false" class="login-btn" @click="goToLogin">
              立即登录
            </el-link>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 用户注册 -->
    <el-dialog v-model="dialogFormVisibleUser" title="用户注册" width="500">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
        label-width="auto" class="demo-ruleForm">
        <el-form-item label="账号" prop="account">
          <el-input v-model="ruleForm.account" />
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 商家注册表单 -->
    <el-dialog v-model="dialogFormVisibleSeller" title="商家入驻" width="800px">
      <el-form :model="sellerForm" :rules="formRules" ref="formRef" label-width="120px" label-position="left"
        status-icon>
        <el-row :gutter="20">
          <!-- 企业信息 -->
          <el-col :span="12">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model="sellerForm.companyName" placeholder="请输入营业执照注册名称" />
            </el-form-item>

            <el-form-item label="用户名" prop="creditCode">
              <el-input v-model="sellerForm.username" placeholder="用户名" />
            </el-form-item>

            <el-form-item label="密码" prop="creditCode">
              <el-input v-model="sellerForm.password" placeholder="密码" />
            </el-form-item>
          </el-col>

          <!-- 联系人信息 -->
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="sellerForm.contactName" placeholder="负责人姓名" />
            </el-form-item>

            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="sellerForm.contactPhone" placeholder="11位手机号码" />
            </el-form-item>

            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="sellerForm.email" placeholder="常用邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 经营信息 -->
        <el-form-item label="主营农产品" prop="mainProducts">
          <el-select v-model="sellerForm.mainProducts" multiple placeholder="请选择主营品类" style="width: 100%">
            <el-option v-for="item in agriculturalCategories" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="sellerForm.address" type="textarea" :rows="2" placeholder="详细经营地址（省市区+街道门牌号）" />
        </el-form-item>

        <!-- 证件上传 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证正面" prop="businessLicense">
              <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1" :on-exceed="handleExceed"
                accept=".jpg,.jpeg,.png">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证反面" prop="idCard">
              <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="2" :on-exceed="handleExceed"
                accept=".jpg,.jpeg,.png">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleSeller = false">取消</el-button>
          <el-button type="primary" @click="submitSellerForm">立即提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { UserFilled, Shop, Plus } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { ElMessage, ElUpload } from 'element-plus'
import { useUserStore } from "@/stores/user.store";
const userStore = useUserStore()
const router = useRouter();
const selectedIdentity = ref<string>("");

const selectIdentity = (type: string) => {
  selectedIdentity.value = type;
  // 实际开发中可以在这里跳转到具体注册页面
  console.log("选择的身份类型:", type);
};

const goToLogin = () => {
  // 跳转到登录页面逻辑
  router.push("/user/login");
};

// 用户注册
let dialogFormVisibleUser = ref(false);
import type { FormInstance, FormRules } from "element-plus";

const ruleFormRef = ref<FormInstance>();

const checkAccount = (rule: any, value: any, callback: any) => {
  console.log(1);
  // 首先检查值是否为空
  if (value === "") {
    callback(new Error("请输入账号"));
  }
  // 检查账户名是否为 "admin"
  if (value === "admin") {
    callback(new Error("账号已注册"));
  } else {
    callback();
  }
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    if (ruleForm.checkPass !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("检查密码");
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== ruleForm.pass) {
    callback(new Error("两次密码不同"));
  } else {
    callback();
  }
};



const rules = reactive<FormRules<typeof ruleForm>>({
  pass: [{ validator: validatePass, trigger: "blur" }],
  checkPass: [{ validator: validatePass2, trigger: "blur" }],
  account: [{ validator: checkAccount, trigger: "blur" }],
});

// 用户注册
const ruleForm = reactive({
  pass: "",
  checkPass: "",
  account: "",
});
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      userStore.handleUserRegister(ruleForm);
      ElMessage.success('注册成功')
      router.push('/user/Login')
    } else {
      console.log("error submit!");
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 商家注册
let dialogFormVisibleSeller = ref(false);
const formRef = ref()

// 表单数据
const sellerForm = reactive({
  companyName: '',
  contactName: '',
  username: '',
  password: '',
  contactPhone: '',
  email: '',
  mainProducts: [],
  address: '',
  idCardUrl: '',
  idCardBackUrl: ''
})

// 农产品分类选项
const agriculturalCategories = ref([
  { value: 'vegetables', label: '新鲜蔬菜' },
  { value: 'fruits', label: '时令水果' },
  { value: 'grains', label: '五谷杂粮' },
  { value: 'meat', label: '禽畜肉类' },
  { value: 'aquatic', label: '水产海鲜' },
  { value: 'processed', label: '农产加工品' }
])

// 验证规则
const formRules = reactive({
  companyName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[0-9A-Z]$/, message: '用户名格式不正确' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[0-9A-Z]$/, message: '密码代码格式不正确' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  mainProducts: [
    { required: true, message: '请至少选择一个主营品类', trigger: 'change' }
  ]
})

// 文件上传处理
const handleExceed = () => {
  ElMessage.warning('最多只能上传一个文件')
}

// 表单提交
const submitSellerForm = async () => {
  try {
    // console.log(sellerForm);
    // await 
    // // 这里添加实际提交逻辑
    // ElMessage.success('提交成功！我们将尽快审核')
    // dialogFormVisibleSeller.value = false
  } catch (error) {
    ElMessage.error('请完善表单信息')
  }
}

</script>

<style lang="scss" scoped>
.register-container {
  height: 100vh;
  // background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
  background: url('@/assets/images/loginbg5.jpg') no-repeat center center;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;

  .register-wrapper {
    width: 100%;
    padding: 20px;
  }

  .register-card {
    border-radius: 20px;
    transition: transform 0.3s ease;

    .register-header {
      text-align: center;
      margin-bottom: 40px;

      .title {
        color: #1a1a1a;
        font-size: 2.5rem;
        margin-bottom: 12px;
        letter-spacing: 1px;
      }

      .subtitle {
        color: #666;
        font-size: 1rem;
      }
    }

    .identity-cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 30px;
      padding: 20px 0;

      .identity-card {
        cursor: pointer;
        border-radius: 15px;
        transition: all 0.3s ease;
        text-align: center;
        padding: 30px 20px;

        &.selected {
          transform: translateY(-5px);
          border: 2px solid;

          &.user-card {
            border-color: #409eff;
            background: rgba(64, 158, 255, 0.05);
          }

          &.merchant-card {
            border-color: #67c23a;
            background: rgba(103, 194, 58, 0.05);
          }
        }

        .card-content {
          .card-icon {
            margin-bottom: 20px;
            color: #4a5568;
          }

          .card-title {
            color: #2d3748;
            margin-bottom: 12px;
            font-size: 1.5rem;
          }

          .card-desc {
            color: #718096;
            font-size: 0.9rem;
            line-height: 1.5;
            margin-bottom: 25px;
          }

          .el-button {
            width: 80%;
            font-weight: bold;
            letter-spacing: 1px;
          }
        }

        &:hover:not(.selected) {
          transform: translateY(-3px);
          box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
      }
    }

    .login-guide {
      text-align: center;
      margin-top: 40px;
      padding-top: 25px;
      border-top: 1px solid #e2e8f0;

      .tip {
        color: #718096;
        margin-right: 8px;
      }

      .login-btn {
        font-weight: 500;
        font-size: 1rem;
        transition: color 0.3s ease;

        &:hover {
          color: #4a9eff;
        }
      }
    }
  }
}
// 商家注册
.el-form-item {
  margin-bottom: 22px;
}

.el-input,
.el-select,
.el-textarea {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  padding: 20px 0 0;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}
</style>
